<template>
  <div class="created_serial list_panel" v-loading="isLoadingTur || isLoadingWor">
    <div class="title_list" :class="activeIndex === 1 ? 'is_left' : 'is_right'">
      <p class="serial_title left_title" @click="changeTitIndex(1)">批次历史序列号 <span v-if="countOfBatch">（{{countOfBatch}}）</span></p>
      <p class="serial_title right_title" @click="changeTitIndex(2)">工单历史序列号 <span v-if="countOfWorkorder">（{{countOfWorkorder}}）</span></p>
    </div>
    <div class="empty_panel" v-if="!turnoverSerialNumbers.length && activeIndex === 1"><span>暂无历史数据</span></div>
    <div class="empty_panel" v-if="!workorderSerialNumbers.length && activeIndex === 2"><span>暂无历史数据</span></div>
    <div class="serial_card_list list_container" v-if="turnoverSerialNumbers.length && activeIndex === 1">
      <div class="serial_card"
           v-for="(item, index) in turnoverSerialNumbers"
           :key="index"
           :class="{'delete_card' : deleteSerialNum === item.serialNumber, 'in_workorder' : activeIndex === 2}">
        <p>{{item.sort}}序列号: {{item.serialNumber}}</p>
        <p class="sub_msg">周转码: DG2019-202-20</p>
        <p class="sub_msg">生成时间: {{item.createDate}}</p>
        <div class="card_btn">
          <i class="iconfont icon-btn_edit" @click="editSerialNumber(item)"></i>
          <i class="iconfont icon-ic_cancel" @click="deleteSerialNumber(item)"></i>
        </div>
      </div>
    </div>
    <div class="serial_card_list list_container" v-if="workorderSerialNumbers.length && activeIndex === 2">
      <div class="serial_card"
           v-for="(item, index) in workorderSerialNumbers"
           :key="index"
           :class="{'delete_card' : deleteSerialNum === item.serialNumber, 'in_workorder' : activeIndex === 2}">
        <p>{{item.sort}}序列号: {{item.serialNumber}}</p>
        <p class="sub_msg">周转码: DG2019-202-20</p>
        <p class="sub_msg">生成时间: {{item.createDate}}</p>
      </div>
    </div>
    <el-dialog
      title="修改序列号"
      width="400px"
      :visible.sync="dialogTableVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      append-to-body
      customClass="mes_dialog"
      @closed="closeEdit">
      <div class="serialNumber_edit">
        <el-form :model="editData" :rules="rules" ref="eidtForm">
          <el-form-item class="form_item" label="前缀:" prop="prefix">
            <div class="input_wapper">
              <el-input
                placeholder="请输入前缀"
                v-model.trim="editData.prefix"
                size="small">
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="后缀:" prop="serialNumber">
            <div class="input_wapper">
              <el-input
                placeholder="请输入后缀"
                v-model.trim="editData.serialNumber"
                size="small">
              </el-input>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer mes_btn">
        <el-button type="primary" @click="save">提交</el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {isOverLength} from '../formValidate'
import {isContainNumOrLetter} from '@/utils/validate'
export default {
  name: 'OldSerialNumber',
  props: {
    workStageMsg: {}
  },
  data() {
    return {
      isLoadingTur: false, // 批次序加载全局loading
      isLoadingWor: false, // 工单加载全局loading
      turnoverSerialNumbers: [], // 批次序列号列表
      workorderSerialNumbers: [], // 工单序列号列表
      serialNumberHistoryList: [], // 生产序列号历史列表
      deleteSerialNum: '', // 当前所删除的序列号
      isInit: false, // 是否初次加载
      editData: {}, // 编辑序列号
      dialogTableVisible: false, // 修改弹窗
      saveStatus: true, // 保存按钮状态
      activeIndex: 1, // 选中标题索引
      countOfBatch: 0, // 批次总条数
      countOfWorkorder: 0, // 工单总条数
      // 修改序列号表单验证条件
      rules: {
        prefix: [
          {required: true, message: '请输入前缀', trigger: 'blur'},
          {validator: isContainNumOrLetter, message: '前缀只能包含字母和数字', trigger: 'change'},
          {validator: isOverLength, message: '前缀长度不能大于20', trigger: 'change'}
        ],
        serialNumber: [
          {required: true, message: '请输入后缀', trigger: 'blur'},
        ],
      },
    }
  },
  mounted() {
    this.getHistorySerialNumber()
  },
  methods: {
    // 选择标题
    changeTitIndex(index) {
      this.activeIndex = index || 1
      this.activeIndex === 1 ? this.getTurnoverSerialNumber() : this.getWorkorderSerialNumber()
    },
    /**
     * 获取历史序列号
     */
    getHistorySerialNumber() {
      this.getTurnoverSerialNumber()
      this.getWorkorderSerialNumber()
    },
    // 获取周转批次序列号
    getTurnoverSerialNumber() {
      this.isLoadingTur = true
      this.turnoverSerialNumbers = []
      let postData = JSON.parse(JSON.stringify(this.workStageMsg))
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnovermaterialserialnumber/turnoverMaterialSerialNumber/getBatchSerialNumber',
        data: postData,
        noCommit: true
      }).then((res) => {
        const list = res.data || []
        this.turnoverSerialNumbers = list
        this.countOfBatch = this.turnoverSerialNumbers.length
        this.$emit('getCount', this.countOfBatch)
        if (this.turnoverSerialNumbers.length && !this.isInit) {
          this.$emit('historyHandle', this.turnoverSerialNumbers[0].prefix)
        }
      }).catch(() => {
        this.turnoverSerialNumbers = []
      }).finally(() => {
        this.isLoadingTur = false
      })
      this.isInit = true
    },
    // 获取工单批次号
    getWorkorderSerialNumber() {
      this.isLoadingWor = true
      this.workorderSerialNumbers = []
      let postData = JSON.parse(JSON.stringify(this.workStageMsg))
      if (postData.turnoverId) delete postData.turnoverId
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnovermaterialserialnumber/turnoverMaterialSerialNumber/getBatchSerialNumber',
        data: postData,
        noCommit: true
      }).then((res) => {
        const list = res.data || []
        const currentTurnoverId = this.workStageMsg.turnoverId || ''
        this.workorderSerialNumbers = list.filter((item) => item.turnoverId !== currentTurnoverId)
        this.countOfWorkorder = this.workorderSerialNumbers.length
      }).catch(() => {
        this.workorderSerialNumbers = []
      }).finally(() => {
        this.isLoadingWor = false
      })
    },
    // 编辑序列号
    editSerialNumber(item) {
      this.dialogTableVisible = true
      this.editData = JSON.parse(JSON.stringify(item))
      const prefixLen = this.editData.prefix.length
      this.editData.serialNumber = this.editData.serialNumber.substring(prefixLen)
    },
    // 删除已生成序列号
    deleteSerialNumber(item) {
      this.confirmOpen('选中的序列号将被删除, 是否继续?', '删除提示').then(() => {
        this.deleteRequest(item.id)
      })
    },
    // 删除序列号请求
    deleteRequest(id) {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnovermaterialserialnumber/turnoverMaterialSerialNumber/deleteBatchSerialNumber',
        data: {id: id},
        noCommit: true
      }).then(() => {
        this.getHistorySerialNumber()
        this.$emit('deleteSerialNumber')
        this.tipMessage('success', '删除成功')
      })
    },
    // 编辑序列号保存
    save() {
      this.$refs['eidtForm'].validate((valid) => {
        if (valid) {
          if (!this.saveStatus) return
          this.saveStatus = false
          let formData = JSON.parse(JSON.stringify(this.editData))
          formData.serialNumber = formData.prefix + formData.serialNumber
          if (formData.serialNumber.length > 29) {
            this.saveStatus = true
            return this.tipMessage('error', '序列号位数不能大于29位')
          }
          const postData = {
            turnoverMaterialSerialNumberList: [
              {
                id: formData.id,
                serialNumber: formData.serialNumber,
                prefix: formData.prefix,
                workorderId: formData.workorderId,
                turnoverId: this.workStageMsg.turnoverId
              }]
          }
          this.$store.dispatch('saveData', {
            method: 'post',
            url: 'a/turnovermaterialserialnumber/turnoverMaterialSerialNumber/saveBatch',
            data: postData,
            noCommit: true
          }).then(() => {
            this.getHistorySerialNumber()
            this.dialogTableVisible = false
            this.tipMessage('success', '修改成功')
          }).finally(() => {
            this.saveStatus = true
          })
        }
      })
    },
    // 关闭编辑弹窗
    closeEdit() {
      this.saveStatus = true
      this.editData = {}
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .title_list{
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #dbe1e8;
    height: 44px;
    padding-left: 14px;
    background-color: #f5f5f5;
    position: relative;
    .serial_title{
      width: 50%;
      line-height: 44px;
      text-align: center;
      cursor:pointer;
    }
    &::after{
      content: '';
      display: block;
      width: 51%;
      position: absolute;
      bottom: 0;
      border-bottom: 2px solid #00b4ff;
      transition: all 0.2s ease;
    }
    &.is_left{
      &::after{
        left: 0;
      }
      .left_title{
        color: #00b4ff;
      }
    }
    &.is_right{
      &::after{
        left: 49%;
      }
      .right_title{
        color: #00b4ff;
      }
    }
  }
  .created_serial{
    width: 34%;
    .serial_card_list{
      padding-right: 22px;
      padding-left: 14px;
      height:calc(100% - 45px);
      overflow-y: auto;
      .serial_card{
        border:@mesBorDefault;
        margin-top: 10px;
        background-color: #fff;
        width: 100%;
        position: relative;
        overflow: hidden;
        min-height: 74px;
        transition: all 0.5s ease;
        padding-bottom: 4px;
        .card_btn{
          width: auto;
          height: 100%;
          position: absolute;
          top:0;
          right:0;
          color:#7e8e9f;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          padding-right: 5px;
          i{
            display: none;
            cursor: pointer;
          }
        }
        &:hover .card_btn i{
          display: block;
        }
        &:first-child{
          margin-top: 15px;
        }
        &:last-child{
          margin-bottom: 20px;
        }
        p{
          padding-left: 10px;
          margin-top: 6px;
          margin-bottom: 0!important;
          font-weight: 600;
          word-break: break-all;
          padding-right: 20px;
          &.sub_msg{
            font-size:12px;
            color: #7e8e9f;
            margin-top: 4px;
            font-weight: normal;
          }
        }
      }
      .in_workorder{
        p{
          padding-right: 0;
        }
      }
      .delete_card{
        height: 0;
        border:none;
      }
    }
  }
  .serialNumber_edit{
    padding-bottom: 10px;
    .el-dialog__body{
      padding-bottom: 0!important;
    }
    .el-form-item__content{
      width: calc(100% - 70px);
    }
    .el-form-item__label{
      width: 80px;
    }
    .el-form-item{
      margin:0;
      display: flex;
      align-items: center;
      &:first-child{
        padding-bottom: 20px;
      }
      .el-input__inner{
        border-radius: 2px;
      }
    }
  }
</style>
